package org.duang.db.sql.parser.decode;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

import org.duang.kit.DataType;
import org.duang.kit.ToolsKit;

public class SqlPropertyDecoder extends SqlDecoder {

	public SqlPropertyDecoder(Map<String, Object> map, Field field){
		super(map, field);
	}
	
	@Override
	public String getFieldName() {
		return field.getName();
	}

	@Override
	public Object getFieldValue() {
		return value;
	}

	@Override
	public boolean isNullField() {
		return null == value;
	}

	@Override
	public void setObj(Object obj) {
		Class<?> fieldType = field.getType();
		try{
			decodeProperty(obj, fieldType);
		}catch(Exception e){
			throw new RuntimeException("设置成员变量["+field.getName()+"]出错！", e);
		}
	}
	
	
	private void decodeProperty(Object obj, Class<?> type) throws Exception{
		Object fieldValue = getFieldValue(); 
		if(ToolsKit.isEmpty(fieldValue)) return;		//如果为null或空字符串,直接退出		
		field.setAccessible(true);
		if (DataType.isString(type)) {			
			field.set(obj, fieldValue.toString());			
		} else if (DataType.isInteger(type)) {
			field.set(obj, Integer.parseInt(fieldValue.toString()));
		} else if (DataType.isIntegerObject(type)) {
			field.set(obj, Integer.valueOf(fieldValue.toString()));
		} else if (DataType.isDouble(type)) {
			field.set(obj, Double.parseDouble(fieldValue.toString()));
		} else if (DataType.isDoubleObject(type)) {
			field.set(obj, Double.valueOf(fieldValue.toString()));
		} else if (DataType.isFloat(type)) {
			field.setFloat(obj, Float.parseFloat(fieldValue.toString()));
		} else if (DataType.isFloatObject(type)) {
			field.set(obj, Float.valueOf(fieldValue.toString()));
		} else if (DataType.isShort(type)) {
			field.setShort(obj, Short.parseShort(fieldValue.toString()));
		} else if (DataType.isShortObject(type)) {
			field.set(obj, Short.valueOf(fieldValue.toString()));
		} else if (DataType.isBoolean(type)) {
			field.set(obj, Boolean.parseBoolean(fieldValue.toString()));
		} else if (DataType.isBooleanObject(type)) {
			field.set(obj, Boolean.valueOf(fieldValue.toString()));
		} else if (DataType.isChar(type)) {
			field.set(obj, fieldValue.toString().charAt(0));
		} else if (DataType.isCharObject(type)) {
			field.set(obj, fieldValue.toString().charAt(0));
		}  else if (DataType.isDate(type)) {
				if(DataType.isTimestamp(fieldValue.getClass())){
					Timestamp time = (Timestamp)fieldValue;
					field.set(obj, new Date(time.getTime()));
				} else {
					Date date = (Date) fieldValue;
					field.set(obj, date);
				}
		} else if (DataType.isTimestamp(type)) {
			Timestamp time = (Timestamp)fieldValue;
			field.set(obj, new Date(time.getTime()));
		} else {
			field.set(obj, value); // for others
		}
	}

}
